package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Role;
import com.itheima.service.UserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * 用户操作
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Reference
    private UserService userService;

    private String username;
    //获得当前登录用户的用户名
    @RequestMapping("/getUsername")
    public Result getUsername(){
        //当Spring security完成认证后，会将当前用户信息保存到框架提供的上下文对象
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        System.out.println(user);
        if(user != null){
            username = user.getUsername();
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,username);
        }

        return new Result(false, MessageConstant.GET_USERNAME_FAIL);
    }

    @RequestMapping("/getMenus")
    public Result getMenus(){
        //根据username查询到user
        com.itheima.pojo.User user = userService.findByUsername(username);
        if (user!=null) {
            Set<Role> roles = user.getRoles();
            for (Role role : roles) {
                LinkedHashSet<Menu> menus = role.getMenus();
                List<Map<String, Object>> list =new ArrayList<>();
                for (Menu menu : menus) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("path",menu.getPath());
                    map.put("title",menu.getName());
                    map.put("icon",menu.getIcon());
                    //子菜单进行遍历
                    List<Menu> children = menu.getChildren();
                    List<Map<String, Object>> childrenList =new ArrayList<>();
                    for (Menu child : children) {
                        Map<String, Object> map1 = new HashMap<>();
                        map1.put("path",child.getPath());
                        map1.put("title",child.getName());
                        map1.put("linkUrl",child.getLinkUrl());
                        childrenList.add(map1);
                    }
                    map.put("children",childrenList);
                    list.add(map);
                }
                //查询到角色关联的菜单
                return new Result(true, MessageConstant.GET_MENU_SUCCESS, list);
            }
        }
        return new Result(false, MessageConstant.GET_MENU_FAIL);
    }

    @RequestMapping("/add")
    public Result add(@RequestBody com.itheima.pojo.User user,Integer[] roleIds){
        try {
            userService.add(user,roleIds);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"新增用户失败");
        }
        return new Result(true,"新增用户成功");
    }

    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        return userService.pageQuery(queryPageBean);
    }

    @RequestMapping("/findById")
    public Result findById(Integer id){
        try {
            com.itheima.pojo.User user = userService.findById(id);
            return new Result(true,"查询用户信息成功",user);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"查询用户信息失败");
        }
    }

        @RequestMapping("/findRoleIdsByUserId")
    public Result findRoleIdsByUserId(Integer id){
        try {
            List<Integer> roleIds = userService.findRoleIdsByUserId(id);
            return new Result(true,"查询角色成功",roleIds);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"查询角色失败");
        }
    }

    @RequestMapping("/edit")
    public Result edit(@RequestBody com.itheima.pojo.User user,Integer[] roleIds){
        try {
            userService.edit(user,roleIds);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"编辑用户信息失败");
        }
        return new Result(true,"编辑用户信息成功");
    }

    @PreAuthorize("hasAuthority('USER_DELETE')")
    @RequestMapping("/delete")
    public Result delete(Integer id){
        try {
            userService.deleteById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"删除用户失败");
        }
        return new Result(true,"删除用户成功");
    }
}
